package com.xpec.c4.service.utility;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Inflater;

import net.sf.cindy.Buffer;
import net.sf.cindy.buffer.BufferFactory;

/**
 * 使用java.util.zip的自带解压缩
 * 
 * @author Bany
 *
 * @since 2009-1-2 下午05:26:16
 *
 */

public class JavaZipInflater {
	
	private Inflater decompresser = new Inflater();
	
	public Buffer decompress(Buffer buffer){
		byte[] input=new byte[buffer.remaining()];
		buffer.get(input);
		byte[] output=decompressBytes(input);
		Buffer outBuffer=BufferFactory.allocate(output.length);
		outBuffer.put(output);
		return outBuffer.flip();
	}

	public byte[] decompressBytes(byte input[]) {
		byte output[] = new byte[0];
		decompresser.reset();
		decompresser.setInput(input);
		ByteArrayOutputStream o = new ByteArrayOutputStream(input.length);
		try {
			byte[] buf = new byte[input.length*2];
			int got;
			while (!decompresser.finished()) {
				got = decompresser.inflate(buf);
				o.write(buf, 0, got);
			}
			output = o.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return output;
	}

}
